"""
边缘优化选择对话框
"""

import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk
import numpy as np
from typing import Optional, Callable, Dict, List

from ..utils import get_logger


class EdgeOptimizationDialog:
    """边缘优化选择对话框"""
    
    def __init__(
        self,
        parent: tk.Tk,
        image: np.ndarray,
        mask: np.ndarray,
        image_processor,
        on_select: Optional[Callable] = None
    ):
        """
        初始化对话框
        
        Args:
            parent: 父窗口
            image: 原始图片 (RGB)
            mask: 掩码
            image_processor: 图像处理器实例
            on_select: 选择回调函数 (selected_method: str, optimized_mask: np.ndarray)
        """
        self.parent = parent
        self.image = image
        self.mask = mask
        # 保存原始mask的引用，确保"原图"选项返回真正的原始mask
        self.original_mask = mask.copy()
        self.image_processor = image_processor
        self.on_select = on_select
        self.logger = get_logger(__name__)
        
        # 创建窗口
        self.window = tk.Toplevel(parent)
        self.window.title("边缘优化选择")
        self.window.geometry("1200x800")
        self.window.transient(parent)
        self.window.grab_set()
        
        # 优化方法定义（10个）
        self.optimization_methods = {
            "original": {
                "name": "原图",
                "description": "未经过边缘优化处理",
                "method": None
            },
            "feather": {
                "name": "羽化边缘",
                "description": "边缘渐变过渡，自然柔和",
                "method": "feather",
                "params": {"feather_amount": 15}
            },
            "feather_gaussian": {
                "name": "羽化+高斯",
                "description": "超柔和边缘，最佳融合",
                "method": "feather_gaussian",
                "params": {"feather_amount": 15, "blur_radius": 7}
            },
            "feather_gaussian_stroke": {
                "name": "羽化+高斯+描边",
                "description": "自动描边，增强边缘",
                "method": "feather_gaussian_stroke",
                "params": {"feather_amount": 15, "blur_radius": 7, "stroke_width": 2}
            },
            "choke": {
                "name": "收缩遮罩",
                "description": "去除白边和杂色",
                "method": "choke",
                "params": {"choke_amount": 2, "blur_radius": 3}
            },
            "decontaminate": {
                "name": "颜色去溢",
                "description": "净化边缘颜色污染",
                "method": "decontaminate",
                "params": {"edge_width": 5, "decontaminate_strength": 0.8}
            },
            "choke_decontaminate": {
                "name": "收缩+去溢",
                "description": "最强去白边效果",
                "method": "choke_decontaminate",
                "params": {"choke_amount": 1, "edge_width": 4, "decontaminate_strength": 0.7, "blur_radius": 3}
            },
            "guided_filter": {
                "name": "引导滤波",
                "description": "保边去噪，保留细节",
                "method": "guided_filter",
                "params": {"radius": 8, "eps": 0.01}
            },
            "custom_smooth_harden": {
                "name": "自定义调节⚙️",
                "description": "可调节平滑和硬化强度",
                "method": "custom_smooth_harden",
                "params": {"smooth_amount": 0.5, "harden_amount": 0.5},
                "adjustable": True  # 标记为可调节参数
            },
            "gaussian": {
                "name": "高斯模糊",
                "description": "快速平滑处理",
                "method": "gaussian",
                "params": {"blur_radius": 5}
            }
        }
        
        # 预处理所有优化结果
        self.optimized_results: Dict[str, np.ndarray] = {}
        self.preview_images: Dict[str, ImageTk.PhotoImage] = {}
        
        # 选中的方法
        self.selected_method = None
        
        # 创建UI
        self._create_ui()
        
        # 在后台生成预览
        self._generate_previews()
    
    def _create_ui(self):
        """创建用户界面"""
        # 标题
        title_frame = ttk.Frame(self.window, padding=10)
        title_frame.pack(fill=tk.X)
        
        ttk.Label(
            title_frame,
            text="选择边缘优化方法",
            font=("Arial", 14, "bold")
        ).pack(side=tk.LEFT)
        
        ttk.Label(
            title_frame,
            text="点击缩略图查看完整预览，然后选择优化方法添加到裁剪库",
            font=("Arial", 10)
        ).pack(side=tk.LEFT, padx=20)
        
        # 顶部缩略图区域 - 横向滚动布局
        thumbnail_container = ttk.Frame(self.window, padding=10)
        thumbnail_container.pack(fill=tk.X)
        
        # 创建画布和滚动条
        canvas_frame = tk.Frame(thumbnail_container, height=220)
        canvas_frame.pack(fill=tk.X)
        
        # 横向滚动条
        h_scrollbar = ttk.Scrollbar(canvas_frame, orient=tk.HORIZONTAL)
        h_scrollbar.pack(side=tk.BOTTOM, fill=tk.X)
        
        # 画布
        thumbnail_canvas = tk.Canvas(
            canvas_frame,
            height=200,
            bg="#f0f0f0",
            highlightthickness=0,
            xscrollcommand=h_scrollbar.set
        )
        thumbnail_canvas.pack(side=tk.TOP, fill=tk.X)
        h_scrollbar.config(command=thumbnail_canvas.xview)
        
        # 内部框架（用于放置所有缩略图）
        thumbnail_inner_frame = ttk.Frame(thumbnail_canvas)
        thumbnail_canvas.create_window(0, 0, anchor=tk.NW, window=thumbnail_inner_frame)
        
        # 所有方法按顺序排列
        self.thumbnail_buttons = {}
        methods = [
            "original", "feather", "feather_gaussian", "feather_gaussian_stroke",
            "choke", "decontaminate", "choke_decontaminate", "guided_filter",
            "custom_smooth_harden", "gaussian"
        ]
        
        for method_key in methods:
            btn_frame = self._create_thumbnail_button(
                thumbnail_inner_frame,
                method_key,
                self.optimization_methods[method_key]
            )
            btn_frame.pack(side=tk.LEFT, padx=5, pady=5)
            self.thumbnail_buttons[method_key] = btn_frame
        
        # 更新滚动区域
        thumbnail_inner_frame.update_idletasks()
        thumbnail_canvas.config(scrollregion=thumbnail_canvas.bbox("all"))
        
        # 支持鼠标滚轮横向滚动
        def on_mousewheel(event):
            thumbnail_canvas.xview_scroll(int(-1 * (event.delta / 120)), "units")
        
        # 绑定鼠标滚轮事件（仅在缩略图区域内有效）
        thumbnail_canvas.bind("<Enter>", lambda e: thumbnail_canvas.bind_all("<MouseWheel>", on_mousewheel))
        thumbnail_canvas.bind("<Leave>", lambda e: thumbnail_canvas.unbind_all("<MouseWheel>"))
        
        # 保存引用以便后续使用
        self.thumbnail_canvas = thumbnail_canvas
        self.thumbnail_inner_frame = thumbnail_inner_frame
        self.mousewheel_handler = on_mousewheel
        
        # 中间预览区域
        preview_container = ttk.Frame(self.window, padding=10)
        preview_container.pack(fill=tk.BOTH, expand=True)
        
        # 预览标题
        self.preview_title = ttk.Label(
            preview_container,
            text="请先选择一个缩略图查看完整预览",
            font=("Arial", 12, "bold")
        )
        self.preview_title.pack(pady=5)
        
        # 预览描述
        self.preview_description = ttk.Label(
            preview_container,
            text="",
            font=("Arial", 10),
            foreground="gray"
        )
        self.preview_description.pack(pady=2)
        
        # 预览画布
        self.preview_canvas = tk.Canvas(
            preview_container,
            bg="#2b2b2b",
            highlightthickness=1,
            highlightbackground="gray"
        )
        self.preview_canvas.pack(fill=tk.BOTH, expand=True, pady=10)
        
        # 参数调节区域（仅对可调节方法显示）
        self.params_frame = ttk.Frame(preview_container, padding=10)
        self.params_frame.pack(fill=tk.X, pady=5)
        self.params_frame.pack_forget()  # 默认隐藏
        
        # 平滑度滑块
        smooth_row = ttk.Frame(self.params_frame)
        smooth_row.pack(fill=tk.X, pady=5)
        
        ttk.Label(smooth_row, text="平滑强度:", font=("Arial", 10, "bold"), width=10).pack(side=tk.LEFT)
        self.smooth_var = tk.DoubleVar(value=0.5)
        self.smooth_scale = ttk.Scale(
            smooth_row,
            from_=0.0,
            to=1.0,
            orient=tk.HORIZONTAL,
            variable=self.smooth_var,
            command=self._on_param_change
        )
        self.smooth_scale.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5)
        self.smooth_value_label = ttk.Label(smooth_row, text="0.50", width=6, font=("Arial", 10))
        self.smooth_value_label.pack(side=tk.LEFT, padx=5)
        ttk.Label(smooth_row, text="(0=锐利 → 1=柔和)", foreground="gray").pack(side=tk.LEFT)
        
        # 硬化度滑块
        harden_row = ttk.Frame(self.params_frame)
        harden_row.pack(fill=tk.X, pady=5)
        
        ttk.Label(harden_row, text="硬化强度:", font=("Arial", 10, "bold"), width=10).pack(side=tk.LEFT)
        self.harden_var = tk.DoubleVar(value=0.5)
        self.harden_scale = ttk.Scale(
            harden_row,
            from_=0.0,
            to=1.0,
            orient=tk.HORIZONTAL,
            variable=self.harden_var,
            command=self._on_param_change
        )
        self.harden_scale.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5)
        self.harden_value_label = ttk.Label(harden_row, text="0.50", width=6, font=("Arial", 10))
        self.harden_value_label.pack(side=tk.LEFT, padx=5)
        ttk.Label(harden_row, text="(0=扩展 → 1=收缩)", foreground="gray").pack(side=tk.LEFT)
        
        # 重置按钮
        reset_row = ttk.Frame(self.params_frame)
        reset_row.pack(fill=tk.X, pady=5)
        ttk.Button(
            reset_row,
            text="重置为默认值",
            command=self._reset_params,
            width=15
        ).pack(side=tk.LEFT, padx=5)
        
        # 提示信息
        ttk.Label(
            reset_row,
            text="💡 调节滑块可实时预览效果",
            foreground="#0066cc",
            font=("Arial", 9, "italic")
        ).pack(side=tk.LEFT, padx=20)
        
        # 底部按钮和状态栏
        button_frame = ttk.Frame(self.window, padding=10)
        button_frame.pack(fill=tk.X)
        
        # 左侧状态标签
        self.status_label = ttk.Label(
            button_frame,
            text="正在生成预览...",
            font=("Arial", 10)
        )
        self.status_label.pack(side=tk.LEFT, padx=10)
        
        # 右侧按钮
        ttk.Button(
            button_frame,
            text="取消",
            command=self._on_cancel,
            bootstyle="secondary",
            width=12
        ).pack(side=tk.RIGHT, padx=5)
        
        self.confirm_btn = ttk.Button(
            button_frame,
            text="确定选择",
            command=self._on_confirm,
            bootstyle="success",
            width=12,
            state=tk.DISABLED
        )
        self.confirm_btn.pack(side=tk.RIGHT, padx=5)
    
    def _create_thumbnail_button(
        self,
        parent: ttk.Frame,
        method_key: str,
        method_info: dict
    ) -> ttk.Frame:
        """
        创建缩略图按钮
        
        Args:
            parent: 父容器
            method_key: 方法键名
            method_info: 方法信息
        
        Returns:
            ttk.Frame: 按钮框架
        """
        # 外层框架
        btn_frame = ttk.Frame(parent, relief=tk.RAISED, borderwidth=2)
        btn_frame.method_key = method_key
        
        # 标题
        ttk.Label(
            btn_frame,
            text=method_info["name"],
            font=("Arial", 10, "bold")
        ).pack(pady=5)
        
        # 缩略图画布
        canvas = tk.Canvas(
            btn_frame,
            bg="#2b2b2b",
            highlightthickness=0,
            width=160,
            height=160
        )
        canvas.pack(pady=5, padx=5)
        btn_frame.canvas = canvas
        
        # 加载中提示
        loading_label = ttk.Label(
            canvas,
            text="生成中...",
            font=("Arial", 9),
            background="#2b2b2b",
            foreground="white"
        )
        canvas.create_window(90, 90, window=loading_label, tags="loading")
        btn_frame.loading_label = loading_label
        
        # 绑定点击事件
        def on_click(event=None):
            self._on_thumbnail_clicked(method_key)
        
        btn_frame.bind("<Button-1>", on_click)
        canvas.bind("<Button-1>", on_click)
        
        # 添加鼠标悬停效果
        def on_enter(event):
            btn_frame.config(relief=tk.SUNKEN, borderwidth=3)
        
        def on_leave(event):
            if self.selected_method != method_key:
                btn_frame.config(relief=tk.RAISED, borderwidth=2)
        
        btn_frame.bind("<Enter>", on_enter)
        btn_frame.bind("<Leave>", on_leave)
        canvas.bind("<Enter>", on_enter)
        canvas.bind("<Leave>", on_leave)
        
        return btn_frame
    
    def _generate_previews(self):
        """生成所有预览图"""
        import threading
        
        def generate():
            try:
                for method_key, method_info in self.optimization_methods.items():
                    # 生成优化结果
                    if method_info["method"] is None:
                        # 原图
                        optimized_mask = self.mask.copy()
                    else:
                        # 应用优化
                        _, optimized_mask = self.image_processor.apply_edge_optimization(
                            self.image,
                            self.mask,
                            method_info["method"],
                            **method_info.get("params", {})
                        )
                    
                    self.optimized_results[method_key] = optimized_mask
                    
                    # 生成预览图（带透明背景）
                    h, w = self.image.shape[:2]
                    preview_image = np.zeros((h, w, 4), dtype=np.uint8)
                    preview_image[optimized_mask, :3] = self.image[optimized_mask]
                    preview_image[optimized_mask, 3] = 255
                    
                    # 裁剪到内容边界
                    preview_image = self._crop_to_content(preview_image, optimized_mask)
                    
                    # 更新UI
                    self.window.after(0, lambda k=method_key, img=preview_image: self._update_preview(k, img))
                
                # 所有预览生成完成
                self.window.after(0, self._on_previews_complete)
                
            except Exception as e:
                self.logger.error(f"生成预览失败: {e}", exc_info=True)
                self.window.after(0, lambda: self.status_label.config(text=f"生成预览失败: {e}"))
        
        threading.Thread(target=generate, daemon=True).start()
    
    def _update_preview(self, method_key: str, preview_image: np.ndarray):
        """
        更新缩略图预览
        
        Args:
            method_key: 方法键名
            preview_image: 预览图片 (RGBA)
        """
        if method_key not in self.thumbnail_buttons:
            return
        
        btn_frame = self.thumbnail_buttons[method_key]
        canvas = btn_frame.canvas
        
        # 删除加载提示
        canvas.delete("loading")
        
        # 获取canvas尺寸
        canvas.update()
        canvas_width = canvas.winfo_width()
        canvas_height = canvas.winfo_height()
        
        if canvas_width <= 1 or canvas_height <= 1:
            canvas_width = 160
            canvas_height = 160
        
        # 调整图片大小
        h, w = preview_image.shape[:2]
        scale = min(canvas_width / w, canvas_height / h) * 0.9
        new_w = int(w * scale)
        new_h = int(h * scale)
        
        import cv2
        resized = cv2.resize(preview_image, (new_w, new_h))
        
        # 创建带背景的预览（棋盘格背景表示透明）
        bg_image = self._create_checkboard_background(canvas_width, canvas_height)
        
        # 计算居中位置
        offset_x = (canvas_width - new_w) // 2
        offset_y = (canvas_height - new_h) // 2
        
        # Alpha混合
        if resized.shape[2] == 4:
            alpha = resized[:, :, 3:4] / 255.0
            rgb = resized[:, :, :3]
            
            y1, y2 = offset_y, offset_y + new_h
            x1, x2 = offset_x, offset_x + new_w
            bg_image[y1:y2, x1:x2] = (
                rgb * alpha + bg_image[y1:y2, x1:x2] * (1 - alpha)
            ).astype(np.uint8)
        
        # 转换为PhotoImage
        pil_image = Image.fromarray(bg_image)
        photo = ImageTk.PhotoImage(pil_image)
        
        # 显示
        canvas.create_image(0, 0, anchor=tk.NW, image=photo)
        canvas.image = photo
        self.preview_images[method_key] = photo
    
    def _create_checkboard_background(self, width: int, height: int, grid_size: int = 20) -> np.ndarray:
        """
        创建棋盘格背景
        
        Args:
            width: 宽度
            height: 高度
            grid_size: 格子大小
        
        Returns:
            np.ndarray: 背景图片 (RGB)
        """
        bg = np.zeros((height, width, 3), dtype=np.uint8)
        
        color1 = 200
        color2 = 220
        
        for i in range(0, height, grid_size):
            for j in range(0, width, grid_size):
                if ((i // grid_size) + (j // grid_size)) % 2 == 0:
                    bg[i:i+grid_size, j:j+grid_size] = color1
                else:
                    bg[i:i+grid_size, j:j+grid_size] = color2
        
        return bg
    
    def _crop_to_content(
        self,
        image: np.ndarray,
        mask: np.ndarray,
        padding: int = 10
    ) -> np.ndarray:
        """
        裁剪到内容边界
        
        Args:
            image: 图片 (RGBA)
            mask: 掩码
            padding: 边距
        
        Returns:
            np.ndarray: 裁剪后的图片
        """
        rows = np.any(mask, axis=1)
        cols = np.any(mask, axis=0)
        
        if not np.any(rows) or not np.any(cols):
            return image
        
        y_min, y_max = np.where(rows)[0][[0, -1]]
        x_min, x_max = np.where(cols)[0][[0, -1]]
        
        h, w = image.shape[:2]
        y_min = max(0, y_min - padding)
        y_max = min(h, y_max + padding + 1)
        x_min = max(0, x_min - padding)
        x_max = min(w, x_max + padding + 1)
        
        return image[y_min:y_max, x_min:x_max]
    
    def _on_previews_complete(self):
        """所有预览生成完成"""
        self.status_label.config(text="预览生成完成，请点击缩略图查看完整预览")
        self.logger.info("边缘优化预览生成完成")
    
    def _on_thumbnail_clicked(self, method_key: str):
        """
        缩略图点击事件
        
        Args:
            method_key: 方法键名
        """
        self.selected_method = method_key
        method_info = self.optimization_methods[method_key]
        
        # 更新所有缩略图的边框状态
        for key, btn_frame in self.thumbnail_buttons.items():
            if key == method_key:
                btn_frame.config(relief=tk.SUNKEN, borderwidth=3)
            else:
                btn_frame.config(relief=tk.RAISED, borderwidth=2)
        
        # 更新预览标题和描述
        self.preview_title.config(text=method_info["name"])
        self.preview_description.config(text=method_info["description"])
        
        # 如果是可调节方法，显示参数调节区域
        if method_info.get("adjustable", False):
            self.params_frame.pack(fill=tk.X, pady=5)
            # 重置参数为默认值
            default_params = method_info.get("params", {})
            self.smooth_var.set(default_params.get("smooth_amount", 0.5))
            self.harden_var.set(default_params.get("harden_amount", 0.5))
            self._update_param_labels()
        else:
            self.params_frame.pack_forget()
        
        # 在预览画布中显示完整图片
        if method_key in self.optimized_results:
            preview_image = self._get_full_preview_image(method_key)
            self._display_full_preview(preview_image)
        
        # 启用确定按钮
        self.confirm_btn.config(state=tk.NORMAL)
        
        self.logger.info(f"用户点击缩略图: {method_info['name']}")
    
    def _get_full_preview_image(self, method_key: str) -> np.ndarray:
        """
        获取完整预览图片
        
        Args:
            method_key: 方法键名
        
        Returns:
            np.ndarray: 预览图片 (RGBA)
        """
        optimized_mask = self.optimized_results[method_key]
        
        # 生成预览图（带透明背景）
        h, w = self.image.shape[:2]
        preview_image = np.zeros((h, w, 4), dtype=np.uint8)
        preview_image[optimized_mask, :3] = self.image[optimized_mask]
        preview_image[optimized_mask, 3] = 255
        
        # 裁剪到内容边界
        preview_image = self._crop_to_content(preview_image, optimized_mask)
        
        return preview_image
    
    def _display_full_preview(self, preview_image: np.ndarray):
        """
        在预览画布中显示完整图片
        
        Args:
            preview_image: 预览图片 (RGBA)
        """
        # 清空画布
        self.preview_canvas.delete("all")
        
        # 获取画布尺寸
        self.preview_canvas.update()
        canvas_width = self.preview_canvas.winfo_width()
        canvas_height = self.preview_canvas.winfo_height()
        
        if canvas_width <= 1 or canvas_height <= 1:
            canvas_width = 800
            canvas_height = 500
        
        # 调整图片大小
        h, w = preview_image.shape[:2]
        scale = min(canvas_width / w, canvas_height / h) * 0.95
        new_w = int(w * scale)
        new_h = int(h * scale)
        
        import cv2
        resized = cv2.resize(preview_image, (new_w, new_h))
        
        # 创建带背景的预览（棋盘格背景表示透明）
        bg_image = self._create_checkboard_background(canvas_width, canvas_height)
        
        # 计算居中位置
        offset_x = (canvas_width - new_w) // 2
        offset_y = (canvas_height - new_h) // 2
        
        # Alpha混合
        if resized.shape[2] == 4:
            alpha = resized[:, :, 3:4] / 255.0
            rgb = resized[:, :, :3]
            
            y1, y2 = offset_y, offset_y + new_h
            x1, x2 = offset_x, offset_x + new_w
            bg_image[y1:y2, x1:x2] = (
                rgb * alpha + bg_image[y1:y2, x1:x2] * (1 - alpha)
            ).astype(np.uint8)
        
        # 转换为PhotoImage
        pil_image = Image.fromarray(bg_image)
        photo = ImageTk.PhotoImage(pil_image)
        
        # 显示
        self.preview_canvas.create_image(0, 0, anchor=tk.NW, image=photo)
        self.preview_canvas.image = photo
    
    def _on_param_change(self, event=None):
        """参数滑块变化回调"""
        if self.selected_method != "custom_smooth_harden":
            return
        
        # 更新显示的数值
        self._update_param_labels()
        
        # 实时重新生成预览
        self._regenerate_custom_preview()
    
    def _update_param_labels(self):
        """更新参数标签显示"""
        self.smooth_value_label.config(text=f"{self.smooth_var.get():.2f}")
        self.harden_value_label.config(text=f"{self.harden_var.get():.2f}")
    
    def _reset_params(self):
        """重置参数为默认值"""
        self.smooth_var.set(0.5)
        self.harden_var.set(0.5)
        self._update_param_labels()
        self._regenerate_custom_preview()
    
    def _regenerate_custom_preview(self):
        """重新生成自定义方法的预览"""
        try:
            self.status_label.config(text="正在更新预览...")
            self.window.update()
            
            # 获取当前参数
            smooth = self.smooth_var.get()
            harden = self.harden_var.get()
            
            # 重新应用优化
            _, optimized_mask = self.image_processor.apply_edge_optimization(
                self.image,
                self.mask,
                "custom_smooth_harden",
                smooth_amount=smooth,
                harden_amount=harden
            )
            
            # 更新结果
            self.optimized_results["custom_smooth_harden"] = optimized_mask
            
            # 更新预览
            preview_image = self._get_full_preview_image("custom_smooth_harden")
            self._display_full_preview(preview_image)
            
            self.status_label.config(text=f"预览已更新 (平滑:{smooth:.2f}, 硬化:{harden:.2f})")
            
        except Exception as e:
            self.logger.error(f"更新预览失败: {e}", exc_info=True)
            self.status_label.config(text=f"更新预览失败: {e}")
    
    def _on_cancel(self):
        """取消按钮回调"""
        self._cleanup()
        self.window.destroy()
    
    def _cleanup(self):
        """清理资源和事件绑定"""
        try:
            # 解绑鼠标滚轮事件
            if hasattr(self, 'thumbnail_canvas'):
                self.thumbnail_canvas.unbind_all("<MouseWheel>")
        except Exception as e:
            self.logger.warning(f"清理事件绑定时出错: {e}")
    
    def _on_confirm(self):
        """确定选择按钮回调"""
        if self.selected_method is None:
            return
        
        # 获取优化后的mask
        # 如果是"原图"选项，直接返回原始mask，不进行任何处理
        if self.selected_method == "original":
            optimized_mask = self.original_mask.copy()
        else:
            optimized_mask = self.optimized_results.get(self.selected_method, self.mask)
        
        method_name = self.optimization_methods[self.selected_method]['name']
        
        # 如果是自定义方法，记录参数
        if self.selected_method == "custom_smooth_harden":
            smooth = self.smooth_var.get()
            harden = self.harden_var.get()
            self.logger.info(
                f"用户确认选择边缘优化方法: {method_name} "
                f"(平滑:{smooth:.2f}, 硬化:{harden:.2f})"
            )
        else:
            self.logger.info(f"用户确认选择边缘优化方法: {method_name}")
        
        # 调用回调
        if self.on_select:
            self.on_select(self.selected_method, optimized_mask)
        
        # 清理并关闭窗口
        self._cleanup()
        self.window.destroy()

